package com.lx.demo.core.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import com.alibaba.dubbo.rpc.service.GenericService;
import com.lx.CommonResultCode;
import com.lx.MsagesException;
import com.lx.Remessages;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by lanyxp on 2020/7/2
 * <P>
 *     dubbo 调用Filter对异常进行统一进行处理 推荐使用配置{@link DubboLogFilter}
 * </P>
 * @see Filter
 */
@Slf4j
@Activate(group = {Constants.PROVIDER, Constants.CONSUMER}, order = 1)
@SuppressWarnings("all")
@Deprecated
public class GolableDubboServiceExceptionFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            String remoteHost = RpcContext.getContext().getRemoteHost();
            long start = System.currentTimeMillis();
            Result result = invoker.invoke(invocation);
            long elapsed = System.currentTimeMillis() - start;
            final String name = invoker.getInterface().getName();
            final String methodName = invocation.getMethodName();
            if (invoker.getUrl() != null) {
                log.debug("调用DUBBO服务 客户端ip:[{}] 服务名称:[{}] 方法名称:[{}] 耗时:[{}]:毫秒", remoteHost, name, methodName, elapsed);
            }
            if (result.hasException() && GenericService.class != invoker.getInterface()) {
                Throwable exception = result.getException();
                if (exception instanceof MsagesException) {
                    MsagesException msagesException = (MsagesException) exception;
                    return new RpcResult(Remessages.fail(msagesException.getCode(), msagesException.getMessage()));
                } else {
                    throw new Exception(exception);
                }
            } else {
                return result;
            }
        } catch (Exception e) {
            log.error("调用DUBBO服务出现异常 -> 系统服务端:{}", e);
            return new RpcResult(Remessages.fail(CommonResultCode.SYSTEM_ERROR));
        }
    }
}
